package thread;

import java.util.ArrayList;

//仓库
class Storage {
	
	// 仓库最大容量
	private final int MAX_SIZE = 100; 
	
	//仓库的房间
	private ArrayList list=new ArrayList();
	
	//生产产品  40
	public void produce(int num) {
		
		synchronized (list) {
			//检查库存
			while (list.size() + num > MAX_SIZE) {
				System.out.println("【要生产的产品数量】:" + num + "\t【库存量】:" + list.size() + "\t暂时不能执行生产任务!");
				try {
					// 条件不满足，生产阻塞
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			 
			for (int i = 0; i < num; i++) {
				list.add(new Object());
			}
			System.out.println("【生产产品】:" + num + "\t【更新现仓储量为】:" + list.size());
			//通知消费者们来消费
			list.notifyAll();  //其实也通知了其他生产者
		} 
	}
	
	// 消费产品
	public void consume(int num) {
		synchronized (list) {
			//检查库存
			// 不满足消费条件
			while (num > list.size()) {
				System.out.println("【要消费的产品数量】:" + num + "\t【库存量】:" + list.size() + "\t暂时不能消费!");
				try {
					list.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			// 消费条件满足，开始消费
			for (int i = 0; i < num; i++) {
				list.remove(0);
			}
			System.out.println("【消费产品】:" + num + "\t【更新现仓储量为】:" + list.size());
			list.notifyAll();  //通知了其他生产者
		} 
	}
}

//生产者
class Producer extends Thread{
	
	public Storage ck;  //仓库
	int num;            //产量
	
	public Producer(Storage ck, int num) {
		this.ck = ck;
		this.num = num;
		this.start();
	} 

	public void run() {
		ck.produce(num);
	}
}

//消费者
class Consumer extends Thread{
	
	public Storage ck;  //仓库
	int num;            //消费数量
	
	public Consumer(Storage ck, int num) {
		this.ck = ck;
		this.num = num;
		this.start();
	} 

	public void run() {
		ck.consume(num);
	}
}

/**
 * 线程间的通信  wait() ,notify/notifyAll() 
 * 生产者 和 消费者  共享一个仓库
 */
public class Test5 {

	public static void main(String[] args) {
		
		Storage storage =new Storage();  //空
		// 生产者对象
		Producer p1 = new Producer(storage,10);
		Producer p2 = new Producer(storage,10);
		Producer p3 = new Producer(storage,10);
		Producer p4 = new Producer(storage,10);
		Producer p5 = new Producer(storage,10);
		Producer p6 = new Producer(storage,10);
		Producer p7 = new Producer(storage,80);

		// 消费者对象
		Consumer c1 = new Consumer(storage,50);
		Consumer c2 = new Consumer(storage,20);
		Consumer c3 = new Consumer(storage,30);

	 

	}

}
